package wsBroker

import (
	"encoding/json"
	"sync"
	"t11Lib/t11Errors"
	"t11Lib/t11Log"
	"亚太-iot-服务器/biz"
	"亚太-iot-服务器/models"
)

var WsHub = func() *wsHub {
	ret := &wsHub{
		hubMap: make(map[string]*WsConn),
		lock:   &sync.Mutex{},
	}
	biz.WsMsgSender = ret
	return ret
}()

type wsHub struct {
	hubMap map[string]*WsConn
	lock   sync.Locker
}

func (hub *wsHub) UnregisterClient(clientId *models.JwtToken) {
	hub.lock.Lock()
	defer hub.lock.Unlock()
	item, ok := hub.hubMap[clientId.ToId()]
	if ok {
		item.close(false)
	}
	delete(hub.hubMap, clientId.ToId())
	t11Log.Debuglnf("[%v] 解除注册", clientId)
}

func (hub *wsHub) RegisterClient(clientId *models.JwtToken, conn *WsConn) {
	hub.lock.Lock()
	defer hub.lock.Unlock()
	item, ok := hub.hubMap[clientId.ToId()]
	if ok {
		item.close(false)
	}
	hub.hubMap[clientId.ToId()] = conn
	t11Log.Debuglnf("[%v] 注册", clientId)
}

func (self *wsHub) SendMsg(clientId *models.JwtToken, data *biz.MqttMsg) t11Errors.T11Error {
	dataBytes, err := json.Marshal(data)
	if err != nil {
		return t11Errors.Wrap(err)
	}
	self.lock.Lock()
	defer self.lock.Unlock()
	client, ok := self.hubMap[clientId.ToId()]
	if !ok {
		return t11Errors.New("ws client 不存在,clientId = %v", clientId)
	}
	return client.WriteData(string(dataBytes))
}
